import store from "../../store";
import React, {useEffect, useState} from "react";
import {addItem as addItemRename, changeValue, getName, getSaga} from "../../reducer/actionsCreater"
import {useDispatch, useSelector, useStore} from "react-redux"

const ReduxCom = () => {
  const dispatch = useDispatch()
  const res = useSelector(state => state)
  const store = useStore()
  const styles = {
    display: 'flex',
    justifyContent: "center",
    alignItem: "center",
    flexDirection: "column"
  }
  const [dataSorce, setDataSorce] = useState(store.getState())
  useEffect(() => {
    store.subscribe(() => {
      setDataSorce(store.getState())
    })

    const action = getSaga()
    // saga执行
    dispatch(action)
  }, [dataSorce])

  const addItem = () => {
    console.log("addItem开始dispatch state：", dataSorce)
    if (dataSorce.value === undefined) {
      return alert("不能空")
    }
    const action = addItemRename()
    dispatch(action)
  }

  const handleInput = (e) => {
    console.log("handleInput开始dispatch state：", dataSorce)
    const action = changeValue(e)
    dispatch(action)
  }
  const getQqName = () => {
    if (dataSorce.value === undefined && "") {
      return alert("不能空")
    }
    console.log(store.getState())
    const action = getName(store.getState().value)
    dispatch(action)
  }
  return (
      <>
        <div style={styles}>
          <input onChange={handleInput} value={dataSorce.value || ""} type="text"/>
          <button onClick={addItem}>+++++</button>
          <button onClick={getQqName}>获取qq名字</button>
          <div>
            {
              dataSorce.list.map((item, index) => (
                  <div key={index}>{item}</div>
              ))
            }
          </div>
        </div>
        <div style={{
          background: "pink",
          width: '100px',
          height: '100px',
          display: 'flex',
          justifyContent: 'center',
          alignItem: 'center'
        }}>
          {dataSorce.name ? dataSorce.name : null}
        </div>
      </>
  )
}
export default ReduxCom

